using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Web.UI;
using Wintellect.PowerCollections;
using System.Web.UI.WebControls;
using System.Collections.ObjectModel;
using System.Web.UI.HtmlControls;

namespace SurveyHost.Core.Controls
{
    [ToolboxItem(false)]
    [ValidationProperty("AnswerText")]
    public class VerticalRadioButtonList : BaseSurveyQuestion
    {
        private RadioButtonList buttons;
        private LiteralControl literal;
        private Collection<AnswerValuePair> _answerValuePairs;
        private const string _helpText = @"This answer type consists of a list of radio buttons displayed vertically in a two column arrangement.  Only one option can be answered at a time.
The configuration consists of a series of option/value pairs.  Each pair is separated from the next using a pipe character ( | ).
The option is separated from the value in each pair by a semicolon ( ; ).  The 'option' text is displayed to the participant.  The 'value' is the stored in the data.
An example of a yes/no question's configuration would be:  yes;1|no;2|No answer;0";

        public override string ConfigurationHelpText
        {
            get
            {
                return _helpText;
            }
        }

        static VerticalRadioButtonList()
        {
        }

        /// <summary>
        /// The list of answers and corresponding values.
        /// </summary>
        /// <remarks>Each item in the collection is a pair of strings.  
        /// The first string is the answer text to display to the user.  The second string is the </remarks>
        public virtual Collection<AnswerValuePair> AnswerValuePairs
        {
            get
            {
                if (_answerValuePairs == null)
                    _answerValuePairs = new Collection<AnswerValuePair>();
                return _answerValuePairs;
            }
        }

        /// <summary>
        /// The response from the user
        /// </summary>
        /// <value></value>
        /// <remarks>Note to extenders:  AnswerText = null indicates the user refused to answer.
        /// </remarks>
        public override string AnswerText
        {
            get
            {
                if (buttons.SelectedIndex == -1 || buttons.SelectedIndex >= _answerValuePairs.Count)
                    return string.Empty;
                return buttons.SelectedValue;
            }
            set
            {
                buttons.SelectedIndex = -1;
                foreach (ListItem i in buttons.Items)
                    if (i.Text.Equals(value, StringComparison.CurrentCultureIgnoreCase))
                    {
                        i.Selected = true;
                        break;
                    }
            }
        }

        /// <summary>
        /// Called by the base class at the time it is appropriate to parse the configuration string,
        /// The configuration can be stored or used to create controls.
        /// </summary>
        protected override void ParseConfigurationString()
        {
            if (AnswerValuePairs.Count != 0)
                return;

            string[] items;
            foreach (string pair in ConfigurationString.Split('|'))
            {
                items = pair.Split(';');
                if (items.Length != 2)
                    continue;
                AnswerValuePairs.Add(new AnswerValuePair(items[0], items[1]));
            }
        }

        /// <summary>
        /// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering.
        /// </summary>
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            ParseConfigurationString();
            HtmlGenericControl questionText = new HtmlGenericControl(HtmlTextWriterTag.Div.ToString());
            HtmlGenericControl questionAnswer = new HtmlGenericControl(HtmlTextWriterTag.Div.ToString());
            questionText.Attributes.Add(HtmlTextWriterAttribute.Class.ToString(), "vRadioButtonQuestionText");
            questionAnswer.Attributes.Add(HtmlTextWriterAttribute.Class.ToString(), "vRadioButtonQuestionAnswer");
            Controls.Add(questionText);
            Controls.Add(questionAnswer);

            literal = new LiteralControl
              {
                  Text =
                      string.Format(
                      QuestionLineFormat, QuestionIndex, QuestionText)
              };

            questionText.Controls.Add(literal);

            buttons = new RadioButtonList();
            buttons.SelectedIndexChanged += SelectedIndexChanged;

            foreach (AnswerValuePair pair in AnswerValuePairs)
                buttons.Items.Add(new ListItem(
                    pair.AnswerText, pair.ValueText));

            buttons.RepeatLayout = RepeatLayout.Table;
            buttons.RepeatColumns = 2;
            buttons.RepeatDirection = RepeatDirection.Vertical;
            questionAnswer.Controls.Add(buttons);

            HtmlGenericControl clearDiv = new HtmlGenericControl(HtmlTextWriterTag.Div.ToString());
            clearDiv.Attributes.Add(HtmlTextWriterAttribute.Class.ToString(), "clearDiv");
            Controls.Add(clearDiv);
        }

        protected void SelectedIndexChanged(object sender, EventArgs e)
        {
            OnAnswerGiven(new AnswerEventArgs(QuestionId, AnswerText));
        }
    }
}
